ERROR = require "./_error.coffee"
PG = require('fckoa/db/pg')
RE = require './_re'
send = require('fckoa/yun/smtp')
USER = require './_model/user'
KEY = require('./_verify_key').mail

module.exports = require('fckoa/router')({
post:{

new: (ctx)->
    {mail,  host} = ctx.request.body
    mail = mail.toLowerCase()
    if mail.length > 250
        raise val:ERROR.MAIL.LENGTH # 邮件地址太长了

    if RE.MAIL.test(mail)
        PG.transaction (trx) ->
            mail_id = await trx.select_val_id('auth.mail', mail)
            if mail_id
                user_id = await trx.select_val_id('auth.user_mail', mail_id)
                if user_id
                    raise val:ERROR.MAIL.EXIST # 邮件已经注册

            await require('./_captcha')(ctx)
            await send {
                to:mail
                from_name:host

                subject:"[#{host}] 请验证邮箱地址，完成注册"
                text:"""\
欢迎注册 #{host} !

请点击下面的链接完成注册（若链接无法点击，请复制到浏览器地址栏）。

#{ctx.request.protocol}://#{host}/auth/mail-#{await KEY.new(mail)}

此链接将在二十四小时后过期失效。"""
            }

            ctx.body = 0
    else
        raise val:ERROR.MAIL.FORMAT # 邮箱格式不正确


}
})
